const mongoose = require('mongoose')
mongoose.Promise = global.Promise;
const db = require('./config/key').mongoURL3;
mongoose.connect(db, { useNewUrlParser: true })
    .then(() => {
        console.log("数据库连接成功");
    })
    .catch(err => {
        console.log(err);
    })
const Schema = mongoose.Schema;
const PersonSchema = new Schema({
    name: {
        type: String,
        // index: true /* 普通索引 */
        unique: true /* 唯一索引 */
    },
    title: {
        type: String,
        trim: true,
    },
    count: String,
    news: {
        type: Number,
        default: 20
    },
    pic: {
        type: String,
        set: function(url) {
            if (!url) return url;
            if (0 !== url.indexOf('http://') && 0 !== url.indexOf('https://')) {
                url = "http://+url"
                return url

            }
        }
    }
})

//自定义实例方法  必须在 实例化Model之前定义 this指向实例化的Schema
PersonSchema.statics.finds = async function(val) {
    if (val) {
        const data = await this.findOne({ name: val });
        console.log(data);
    } else {
        const data = await this.find();
        console.log(data);
    }
};
const Persons = mongoose.model('Persons', PersonSchema)
var use1 = { name: 'webpeck', title: 'node', count: '垃xxxx圾', news: 900, pic: 'xiaohuo.onlin' }
async function add(val) {
    const data = await Persons(val).save()
    console.log(data);
}
// add(use1)
// Persons.remove().then(res => console.log(res))
//     Persons.findOne({ name: 'vue' }).then(res => console.log(res))
// Persons.find().then(res => console.log(res.length))
// 内置方法 ：静态方法  实例方法
// 调用自定义静态方法,
let count = "count";
// Persons.finds('垃ssss圾', count)
// Persons.findOne({ count: '垃xxxx圾' }).then(res => console.log(res))